package com.example.tool.task;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.select.Elements;
import java.io.*;
import java.util.*;

/**
 * @ClassName QCCdemo
 * @Author 13403
 * @Date 2022/8/814:39
 * @Version 1.0
 **/
public class QCCdemo {

    public static void main(String[] args) throws Exception {
        String path="C:/Users/13403/Desktop/qcc.xlsx";//获取客户名称的文件
        String filePath = "C:/Users/13403/Desktop/qccdata.xlsx";//写入的文件
        QCCdemo qcCdemo = new QCCdemo();
        List<Map<String, String>> list= getNameList(path);
        List<Map<String, String>> datalist= new ArrayList<>();
        //i为第几个数据，出问题可以直接从具体数据开始爬
        for (int i = 29; i <list.size(); i++) {
            try {
                Thread.sleep(6000);
                Random random = new Random();
                int i1 = (random.nextInt(10)+1)*1000;
                Thread.sleep(i1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            String name = list.get(i).get("客户名称");
            System.out.println("当前是第"+i+"个爬数据");
            Map<String, String> dataByName = qcCdemo.getDataByName(name, qcCdemo);
            datalist.add(dataByName);
            qcCdemo.inserSheetData(filePath,i+1,dataByName);
        }
        System.out.println("=================");

    }

    /**
     * 最外层方法，获取最终数据
     * @param name
     * @param qcCdemo
     * @return
     */
    private Map<String, String> getDataByName(String name,QCCdemo qcCdemo)  {
        Map<String, String> stringStringHashMap=new HashMap<>();
        stringStringHashMap.put("客户名称",name);
        try {
            String result = qcCdemo.sentQcc(name);
            Map<String, String> map=new HashMap<>();
            map.put("统一社会信用代码","统一社会信用代码");
            map.put("成立日期","成立日期");
            map.put("法定代表人","法定代表人");
            map.put("经营范围","经营范围");
            map.put("名称",name);
            Document parse = Jsoup.parse(result);
            //名称
            Elements nameclass = parse.getElementsByClass("title copy-value");
            String corporateName = nameclass.get(0).getElementsByTag("em").text().replaceAll(" ","");
            //信用代码，法人，成立日期
            Elements three = parse.getElementsByClass("rline over-rline");
            Elements f = three.get(0).getElementsByClass("f");
            stringStringHashMap = qcCdemo.getFtext(f,map);
            //经营范围
            Elements elementsByClass = parse.getElementsByClass("hit-reasons");
            String sale = elementsByClass.get(0).getElementsByClass("sf").text();
            if (sale.contains("经营范围：")){
                String[] split = sale.split("经营范围：");
                stringStringHashMap.put("经营范围",split[1]);
            }else {
                stringStringHashMap.put("经营范围",null);
            }
            System.out.println(stringStringHashMap.toString());
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (stringStringHashMap.get("客户名称")==null){
                stringStringHashMap.put("客户名称",name);
            }
            System.out.println(stringStringHashMap.toString());
            return stringStringHashMap;
        }
    }


    /**
     * 传入节点数据和所需的map，返回结果
     * @param f
     * @param map
     * @return
     */
    private HashMap<String, String> getFtext(Elements f,Map<String, String> map) {
        HashMap<String, String> stringStringHashMap=  new HashMap<>();
        for (int i = 0; i <f.size() ; i++) {
            Element childs=f.get(i);
            String replaceAll = childs.childNodes().get(0).toString().replaceAll(" ", "").replaceAll("：", "");
            if (map.get(replaceAll)!=null){
                String node = childs.childNodes().get(1).childNode(0).toString();
                String s = map.get(replaceAll);
                if ("统一社会信用代码".equals(map.get(replaceAll))){
                    stringStringHashMap.put(replaceAll,Jsoup.parse(node).getElementsByClass("copy-value").text());
                }
                if ("法定代表人".equals(map.get(replaceAll))){
                    Node node1 = childs.childNodes().get(1).childNode(0).childNode(0);
                    String person = node1.childNode(0).toString();
                    stringStringHashMap.put(replaceAll,person);
                }
                if ("成立日期".equals(map.get(replaceAll))){
                    stringStringHashMap.put(replaceAll,node);
                }
            }
        }
        return stringStringHashMap;
    }



    public String  sentQcc(String name) throws IOException {

        String url="https://www.qcc.com/web/search?key="+name;
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpGet get = new HttpGet(url);
        get.addHeader("accept","*/*");
        get.addHeader("accept-encoding","gzip, deflate, br");
        get.addHeader("accept-language","zh-CN");
        get.addHeader("user-agent","ApiPOST Runtime +https://www.apipost.cn");
        get.addHeader("connection","keep-alive");
        get.addHeader("cookie", "acw_tc=b47a4eb716599405544446736e2a5728f8909ebe828c833d850a8ab731; QCCSESSID=6ccc3c74ba48cab1f7a63765e4; qcc_did=eae3bec0-d301-4881-8ecc-1ec336525091; UM_distinctid=1827c2b5613137e-0f230e21e83364-26021a51-1fa400-1827c2b56141941; CNZZDATA1254842228=909089886-1659937162-%7C1659937535;QCCSESSID=6ccc3c74ba48cab1f7a63765e4;QCCSESSID=6ccc3c74ba48cab1f7a63765e4");
        HttpResponse response = httpClient.execute(get);
        return EntityUtils.toString(response.getEntity());
   }

    /**
     * 传入excel,获得公司名称
     * @param path
     * @return
     */
    private static List<Map<String, String>> getNameList(String path) throws FileNotFoundException {
        File file = new File(path);
        String name = file.getName();
        FileInputStream fileInputStream = new FileInputStream(file);
        Map<String, Integer> map=new HashMap();
        map.put("客户名称",0);
        List<Map<String,String>> list = ExcelUtil.parseExcel(fileInputStream, name, 0, 0, 1, map);
        return list;
    }


    /**
     * 从第几行写入数据
     * @param rowNum
     * @param data
     * @throws Exception
     */
    public  void inserSheetData(String filePath,Integer rowNum,Map<String, String> data) throws Exception {
        FileInputStream fs=new FileInputStream(filePath);
        XSSFWorkbook xssfWorkbook = new XSSFWorkbook(fs);
        //获取到工作表，因为一个excel可能有多个工作表
        XSSFSheet InsertSheet = xssfWorkbook.getSheetAt(0);
        //向文件中写入数据
        FileOutputStream out=new FileOutputStream(filePath);
        //在指定行后追加数据
        XSSFRow  row=InsertSheet.getRow(rowNum);
        //设置第一个（从0开始）单元格的数据
        row.createCell(11).setCellValue(data.get("客户名称"));
        row.createCell(12).setCellValue(data.get("统一社会信用代码"));
        row.createCell(13).setCellValue(data.get("法定代表人"));
        row.createCell(14).setCellValue(data.get("成立日期"));
        row.createCell(15).setCellValue(data.get("经营范围"));
        out.flush();
        xssfWorkbook.write(out);
        out.close();
    }


}
